#include "MqttClient.h"

#include <QDateTime>
#include <QRandomGenerator>
#include <QThread>
#include <QJsonDocument>

MqttClient::MqttClient()
{
    this->m_client = new QMqttClient();
    this->m_client->setHostname("192.168.234.130");
    this->m_client->setPort(1883);
    this->m_client->setUsername("sleep");
    this->m_client->setPassword("520520");
    this->m_client->setClientId(this->get_client_id());

    this->m_client->connectToHost();
    connect(this->m_client, &QMqttClient::connected, this, [=](){
        qDebug() << "mqtt连接成功" << __LINE__ << __FILE_NAME__;
        auto subscription_data = this->m_client->subscribe(QMqttTopicFilter("IOT_DM/data/#"), 1);
        if(subscription_data)
        {
            qDebug() << "主题 IOT_DM/data/# 订阅成功" << __LINE__ << __FILE_NAME__;
            connect(subscription_data, &QMqttSubscription::messageReceived, this, [=](const QMqttMessage &message) {

                emit this->data_recived(this->byteArreyToJsonObject(message.payload()));
            });
        }
    });
}

MqttClient& MqttClient::getInstance()
{
    static MqttClient instance;
    return instance;
}

QString MqttClient::get_client_id()
{
    QDateTime currentTime = QDateTime::currentDateTime();
    QString timeStr = currentTime.toString("yyyy_MM_dd_hh_mm_ss");
    int randomNum = QRandomGenerator::global()->bounded(10001);
    return QString("%1_%2").arg(timeStr).arg(randomNum);
}

QJsonObject MqttClient::byteArreyToJsonObject(QByteArray data)
{
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error != QJsonParseError::NoError)
    {
        qDebug() << "JSON 解析失败：" << parseError.errorString() << " 位置：" << parseError.offset;
        return QJsonObject();
    }

    if (!doc.isObject())
    {
        qDebug() << "JSON 文档不是对象类型";
        return QJsonObject();
    }

    return doc.object();
}

